package com.mldong.wxauth.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mldong.wxauth.dto.LoginDTO;
import com.mldong.wxauth.entity.User;
import com.mldong.wxauth.mapper.UserMapper;
import com.mldong.wxauth.service.UserService;
import com.mldong.wxauth.token.ITokenStore;
import com.mldong.wxauth.tool.AssertTool;
import com.mldong.wxauth.vo.TokenVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author mldong
 * @date 2022/1/4
 */
@Service
@AllArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private final ITokenStore tokenStore;
    @Override
    public TokenVO login(LoginDTO dto) {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class)
                .eq(User::getUserName,dto.getUserName())
                .eq(User::getPassword, SecureUtil.md5(dto.getPassword()));
        User user = baseMapper.selectOne(queryWrapper);
        if(user == null) {
            AssertTool.throwBiz("用户名或密码不正确");
        }
        TokenVO vo = new TokenVO();
        vo.setUserId(user.getId());
        vo.setUserName(user.getUserName());
        vo.setAvatar(user.getAvatar());
        vo.setAccessToken(UUID.randomUUID().toString());
        tokenStore.set(vo);
        return vo;
    }
}
